Fetch Function
Description
fetchFunction
is a utility function designed to simplify making HTTP requests within a JavaScript application. It allows you to specify a URL and request options, and handles the fetch operation with built-in support for request and response interception. It's defined inside api.js file present in your directory.
Parameters:
url: A string representing the endpoint URL to which the request will be made.
options: An object containing various options for the request, such as method, headers, body, etc.
Return Value:
A Promise that resolves with the parsed JSON response from the server.
Interceptors:
Request Interceptor: You can modify the request before it is sent to the server by updating the
options
object. For example, you can add custom headers, authentication tokens, etc.Response Interceptor: You can modify the response received from the server before it's returned to the calling code. This can be useful for handling errors, logging, or transforming the response data.
Note:
This function relies on the global
fetch
function, which is commonly available in modern browsers and can be polyfilled for compatibility with older browsers.Make sure to set the
process.env.API_URL
variable to the base URL of your API before using this function.
Fetch Function Benefits
🔧 Interceptors
Request and response interceptors for custom logic
🛡️ Error Handling
Centralized error handling and response validation
⚙️ Configuration
Easy base URL and header configuration
Fetch Function Demo
This demo shows how to use Catalyst's fetchFunction utility with request and response interceptors. Click the buttons below to test different scenarios.
Interceptor Log
No interceptors logged yet. Click a button above to see request and response interceptors in action.
Watch how the fetchFunction processes requests and responses in real-time.
Code Example
Fetch Function Implementation (api.js)
const fetchFunction = (url, options = {}) => { let baseURL = process.env.API_URL let finalUrl = baseURL + url // Request Interceptor - modify request here options.headers = { 'Content-Type': 'application/json', 'X-Custom-Header': 'catalyst-demo', ...options.headers } return fetch(finalUrl, options) .then(response => { return response.json().then(parsedResponse => { // Response Interceptor - modify response here if (parsedResponse.error) { throw new Error(parsedResponse.error.message); } return parsedResponse }) }) } export default fetchFunction
Usage in Component
import fetchFunction from '@api' const MyComponent = () => { const [data, setData] = useState(null) const fetchData = async () => { try { const result = await fetchFunction('/api/posts') setData(result) } catch (error) { console.error('Fetch error:', error) } } return ( <div> <button onClick={fetchData}>Fetch Data</button> {data && <pre>{JSON.stringify(data, null, 2)}</pre>} </div> ) }